<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;

class Api extends Controller
{
    public function __construct(Request $request){
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }

    //获取对应的地区信息
    public function getprovinces(Request $request)
    {
        $data = $request->param();
        $tables = $data['tables'];//表名
        $did = $data['id'];//查询的id
        $map = array();
        if ($request->isPost()) {
            switch ($tables) {
                case 'provinces'://省份
                    $map['country_id'] = array('in', $did);
                    break;
                case 'city'://城市
                    $map['province_id'] = array('in', $did);
                    break;
                case 'town'://地区
                    $map['city_id'] = array('in', $did);
                    break;
                case 'street'://街道
                    $map['town_id'] = array('in', $did);
                    break;
                default:
                    $map = array();
                    break;
            }
            $data = Db::name($tables)->where($map)->select();
            return json_encode($data);
        }
    }

    //获取分类下面的属性id
    public function getcoattr(Request $request)
    {
        $res = $request->param();
        $cotype = $res['cotype'];//分类名称
        $rescoa = array();
        //匹配公司类型属性
        $where['b.cotype_ids'] = array('like', '%' . $cotype . '%');
        $where['b.person'] = 0;//使用公司的属性
        //获取分类名称
        $where['a.lang'] = $res['lang'];//语言标志
        $join = [
            ['nt_coattr b', 'a.mkey=b.mkey']
        ];
        $table = 'multi_lang';
        $coarr = getmultidata($table, $join, $where)['data'];//属性信息
        //获取对应的属性中值，select,text
        foreach ($coarr as $cokey => $covalue) {
            if ($covalue['is_text'] == 1) {
                //select框
                $res = Db::name('coattr_select')->where('coattr_id', $covalue['id'])->select();
                foreach ($res as $reskey => $resvalue) {
                    $coarr[$cokey]['textselect'][] = array('content' => $resvalue['option_text'], 'id' => $resvalue['id']);
                }
            } else if ($covalue['is_text'] == 0) {
                //文本框
                $coarr[$cokey]['textselect'][] = array();
            }
        }
        //对获取的select进行处理
        echo json_encode($coarr);
    }

    //处理语言
    public function lang()
    {
        return is_lang($_GET['lang_type']);
    }

    //返回列表时，判断联系人和银行是否含有值
    public function isbanklink(Request $request)
    {
        $data = $request->param();
        if ($request->isPost() && $request->isAjax() && isset($data['status'])) {
            $colink = Db::name('linkman')->where('co_id', 0)->select();//联系人
            $cobank = Db::name('co_bank')->where('co_id', 0)->select();//银行表
            if ($colink || $cobank) {
                return array('code' => '1', 'status' => '你有未保存的内容，是否确认离开？', 'yes' => '是', 'no' => '否');
            }
        } elseif ($request->isPost() && $request->isAjax() && isset($data['isexist'])) {
            //将coid的数据清除掉
            linkbankhandle(0);
        }
    }

    //获取对应国家的省份
    public function getpro(Request $request)
    {
        $res = $request->param();
        $table = $res['table'];
        $proid = $res['pro_id'];
        switch ($table) {
            case 'provinces':
                //获取对应国家的省份
                if (!$proid) {
                    $data = Db:: name($table)->select();
                } else {
                    $data = Db:: name($table)->where('country_id', $proid)->select();
                }
                break;
            case 'city':
                //获取对应省份的城市
                if (!$proid) {
                    $data = Db:: name($table)->select();
                } else {
                    $data = Db:: name($table)->where('province_id', $proid)->select();
                }
                break;
            case 'town':
                //获取城市下的城镇
                if (!$proid) {
                    $data = Db:: name($table)->select();
                } else {
                    $data = Db:: name($table)->where('city_id', $proid)->select();
                }
                break;
            case 'admin':
                $data = Db:: name($table)->field('id,nickname')->where('position_id', $proid)->select();
                break;
        }
        echo json_encode($data);
    }

    //获取对应国家下的职务和对应国家下的部门
    public function postionfrmaes(Request $request)
    {
        $data = $request->param();
        if ($request->isPost() && $request->isAjax()) {
            $table = $data['table'];
            $lang = $data['lang'];
            $country_id = $data['country_id'];
            $datares = getFrames($table, $lang, $country_id);
            echo json_encode($datares);
        }
    }

    // 根据公司ID(company_id)，获取采购合同信息
    public function getBuyPo(Request $request)
    {
        $data = $request->param();
        if (isset($data['company_id']) && $data['company_id']) $where['zu.company_id'] = $data['company_id'];
        if (isset($data['po_ids']) && $data['po_ids']) $where['zu.id'] = ['in', $data['po_ids']];
        $where['zu.finish_day'] = isset($data['finish_day']) && $data['finish_day'] > 0 ? $data['finish_day'] : 0;
        $buyPoList = model('Buy')->getBuyPo($where, is_lang(), ['zu.id,zu.delivery_day,zu.paid_sum,zu.price_sum,zu.cost_sum']);
        $returnData = [];
        if (!empty($buyPoList)) $returnData = model('Buy')->getPaypoarr($buyPoList, 'add');
        echo json_encode($returnData);
    }

    // 根据合同ID 获取详情
    public function getBuyPoInfo(Request $request)
    {
        $data = $request->param();
        if (!isset($data['po_id']) && empty($data['po_id'])) return json_encode(array('code' => 500, 'msg' =>lang('please_select_a_contract')));
        $where['zu.id'] = $data['po_id'];
        $returnData = model('Buy')->getBuyPo($where, is_lang());
        if (!empty($returnData)) {
            foreach ($returnData as $k => $v) {
                $terms = getDatas('buy_po_terms', ['*'], ['po_id' => $v['id']]);
                if (!empty($terms)) {
                    foreach ($terms as $k1 => $v1) {
                        $returnData[$k]['terms'][$v1['type']]['id'] = $v1['id'];
                        $returnData[$k]['terms'][$v1['type']]['content'] = $v1['content'];
                    }
                }

                $buy_po_logs = getDatas('buy_po_logs', ['*'], ['po_id' => $v['id']]);
                if (!empty($buy_po_logs)) {
                    foreach ($buy_po_logs as $k2 => $v2) {
                        $returnData[$k]['buy_po_logs'][$k2]['content'] = $v2['content'];
                        $returnData[$k]['buy_po_logs'][$k2]['happen_at'] = getTimeDates($v2['happen_at'], 9, is_lang());
                        $returnData[$k]['buy_po_logs'][$k2]['admin_name'] = $v2['admin_id'] == '' ? '-' : getinfo($v2['admin_id'], 'admin')['nickname'];//编辑者
                    }
                }
                $buypoarr = getDatas('buy_po_pay', ['*'], ['po_id' => $v['id']]);
                $returnData[$k]['buypoarr_amount'] = 0;
                if (!empty($buypoarr)) {
                    foreach ($buypoarr as $k3 => $v3) {
                        $returnData[$k]['buypoarr'][$k3]['amount'] = $v3['amount'];
                        $returnData[$k]['buypoarr'][$k3]['pay_day'] = getTimeDates($v3['pay_day'], 9, is_lang());
                        $returnData[$k]['buypoarr'][$k3]['percent'] = $v3['percent'];
                        $returnData[$k]['buypoarr_amount'] += $v3['amount'];
                    }
                }

                // 获取其他费用代支付信息
                $cost_list = getDatas('buy_po_cost', ['*'], ['po_id' => $v['id']]);
                $returnData[$k]['cost_amount'] = 0;
                if (!empty($cost_list)) {
                    foreach ($cost_list as $k4 => $v4) {
                        $returnData[$k]['cost_list'][$k4]['amount'] = $v4['amount'];
                        $returnData[$k]['cost_list'][$k4]['remarks'] = $v4['remarks'];
                        $returnData[$k]['cost_list'][$k4]['is_apportion'] = $v4['apportion'] == 1 ? 'o' : '-'; // 分摊
                        $returnData[$k]['cost_list'][$k4]['replace_pay'] = $v4['is_replace_pay'] == 1 ? 'o' : '-'; //代付
                        $returnData[$k]['cost_amount'] += $v4['amount'];
                    }
                }

                // h获取支付流水信息
                $join = [['fin_co2buy f', 'zu.fin_co2buy_id = f.id'], ['accounts a', 'f.account_id = a.id']];
                $fin_co2buy_po = getSearch('fin_co2buy_po', 'zu', ['zu.*,f.happen_day,f.create_id,a.bankname,a.account_name,a.account_num'], ['po_id' => $v['id']], $join, 'zu.id desc');
                $returnData[$k]['fin_co2buy_po_amount'] = 0;
                if (!empty($fin_co2buy_po)) {
                    foreach ($fin_co2buy_po as $k5 => $v5) {
                        $returnData[$k]['fin_co2buy_po'][$k5] = $v5;
                        $returnData[$k]['fin_co2buy_po'][$k5]['happen_day'] = explode(' ', getTimeDates($v5['happen_day'], 9, is_lang()))[0];
                        $returnData[$k]['fin_co2buy_po'][$k5]['create_name'] = $v5['create_id'] == '' ? '-' : getinfo($v5['create_id'], 'admin')['nickname'];//编辑者
                        $returnData[$k]['fin_co2buy_po_amount'] += $v5['amount'];
                    }
                }
                // 获取收款账号信息
                $join1 = [['fin_co2buy f', 'zu.fin_co2buy_id = f.id'], ['banks b', 'f.bank_id = b.id'], ['co_bank cb', 'b.id = cb.banks_id']];
                $content_sum = getSearch('fin_co2buy_po', 'zu', ['b.name,cb.bankname,cb.account_name,cb.account_num'], ['po_id' => $v['id']], $join1, 'zu.id desc');
                if (!empty($content_sum)) {
                    $returnData[$k]['content_sum'] = $content_sum[0];
                } else {
                    $returnData[$k]['content_sum']['name'] = '';
                    $returnData[$k]['content_sum']['bankname'] = '';
                    $returnData[$k]['content_sum']['account_name'] = '';
                    $returnData[$k]['content_sum']['account_num'] = '';
                }

                $returnData[$k]['plan_sum'] = count($returnData[$k]['buy_plan']);
                $returnData[$k]['weifu_sum'] = $returnData[$k]['buypoarr_amount'] + $returnData[$k]['cost_amount'] - $returnData[$k]['fin_co2buy_po_amount'];
            }
        }
        echo json_encode($returnData[0]);
    }


    // 获取 付款登记 采购应付款项
    public function getBuyPo_pain(Request $request)
    {
        $data = $request->param();
        /* $data['date']['year'] = 2019; */
        // $data['date']['month'] = 12;
        $delivery_at_start = isset($data['date']['year']) && isset($data['date']['month']) ? mktime(0, 0, 0, date($data['date']['month']), 1, date($data['date']['year'])) : strtotime(date('Y-m-01'));
        $delivery_at_end = isset($data['date']['year']) && isset($data['date']['month']) ? mktime(23, 59, 59, date($data['date']['month']), date('t'), date($data['date']['year'])) : mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        $where['zu.delivery_day'] = ['between', $delivery_at_start . ',' . $delivery_at_end];
        $where['zu.finish_day'] = 0;
        $buyPoList = model('Buy')->getBuyPo($where, is_lang(), ['zu.id,zu.company_id,zu.delivery_day,zu.paid_sum,zu.price_sum,zu.cost_sum']);

        $returnData = [];
        $returnDatass = [];
        $size = 0;
        $returnDatass['page']['page'] = 1;
        if (!empty($buyPoList)) {
            $returnData = model('Buy')->getPaypoarr($buyPoList);
            if (!empty($returnData)) {
                foreach ($returnData as $k => $v) {
                    $returnDatas[$v['company_name']][] = $v;
                }
            }
            $size = count($returnDatas);
            // 获取分页数据
            if (isset($data['page']) && isset($data['limit'])) {
                $returnDatass['list'] = array_slice($returnDatas, $data['limit'] * ($data['page'] - 1), $data['limit']);
                $returnDatass['page']['page'] = $data['page'];
            } else {
                $returnDatass['list'] = $returnDatas;
                $returnDatass['page']['page'] = 1;
            }
        }
        $returnDatass['page']['size'] = $size;

        echo json_encode($returnDatass);
    }

    // 根据流水ID获取该流水下公司的合同，获取当前流水合同ID及之后的合同信息
    public function getBuyPoAndCompany(Request $request)
    {
        $data = $request->param();
        if (!isset($data['fin_co2buy_id']) && !empty($data['fin_co2buy_id'])) return json_encode(array('code' => 500, 'msg' => '请选择正确的财务流水'));
        if (!isset($data['company_id']) && !empty($data['company_id'])) return json_encode(array('code' => 500, 'msg' => '请选择正确的财务流水'));
        $po_ids = getGroup('fin_co2buy_po', ['po_id'], ['fin_co2buy_id' => $data['fin_co2buy_id']], 'po_id');
        if (!empty($po_ids)) {
            $po_ids = array_column($po_ids, 'po_id');
            $po_idstr = implode(',', $po_ids);
        }
        $where['zu.finish_day'] = 0;
        $whereOr['zu.id'] = ['in', $po_idstr];
        $buyPoList = model('Buy')->getBuyPo($where, is_lang(), ['zu.id,zu.delivery_day,zu.paid_sum,zu.price_sum,zu.cost_sum'], $whereOr);
        $returnData = [];
        if (!empty($buyPoList)) $returnData = model('Buy')->getPaypoarr($buyPoList);
        foreach ($returnData as $k => $v) {
            if (!empty($v['paypoarr'])) {
                foreach ($v['paypoarr'] as $k1 => $v1) {
                    // 获取当前流水ID下，付款安排被支付的数额
                    $fin_co2buy_amount = getValue('fin_co2buy_po', ['buy_po_payId' => $v1['id'], 'fin_co2buy_id' => $data['fin_co2buy_id']], 'amount');
                    // 获取当前支付安排已经支付得历史流水(当前支付流水不在内)
                    // $amount_all = getDatas('fin_co2buy_po',['amount'],['buy_po_payId'=>$v1['id'],'fin_co2buy_id'=>['not in',$data['fin_co2buy_id']]]);
                    // $amount_sum = 0;
                    // if(!empty($amount_all)){
                    //     foreach ($amount_all as $k2 => $v2) {
                    //         $amount_sum+=$v2['amount'];
                    //     }
                    // }

                    $amount_sum = Db::name('fin_co2buy_po')->where(['buy_po_payId' => $v1['id'], 'fin_co2buy_id' => ['not in', $data['fin_co2buy_id']]])->sum('amount');
                    $has = hasData('fin_co2buy_po', ['fin_co2buy_id' => $data['fin_co2buy_id'], 'buy_po_payId' => $v1['id']]);
                    if ($v1['amount'] - $amount_sum == 0 && !$has) {
                        unset($returnData[$k]['paypoarr'][$k1]);
                    } else {
                        $returnData[$k]['paypoarr'][$k1]['price'] = $fin_co2buy_amount;
                        $returnData[$k]['paypoarr'][$k1]['amount'] = $v1['amount'] - $amount_sum;
                        $returnData[$k]['paypoarr'][$k1]['paid'] = $v1['paid'] - $fin_co2buy_amount;
                    }

                }
            }
            if (!empty($v['cost_list'])) {
                // dump($v['cost_list']);die;
                // 获取当前流水ID下，其他费用代付的被支付的数额
                $fin_co2buy_costamount = getValue('fin_co2buy_po', ['buy_po_payId' => 0, 'fin_co2buy_id' => $data['fin_co2buy_id'], 'po_id' => $v['id']], 'amount');
                // 获取当前其他费用代父款已经支付得历史流水(当前支付流水不在内)
                // $costamount_all = getDatas('fin_co2buy_po',['amount'],['buy_po_payId'=>0,'fin_co2buy_id'=>['not in',$data['fin_co2buy_id']],'po_id'=>$v['id']]);
                // $costamount_sum = 0;
                // if(!empty($costamount_all)){
                //     foreach ($costamount_all as $k3 => $v3) {
                //         $costamount_sum+=$v3['amount'];
                //     }
                // }
                $costamount_sum = Db::name('fin_co2buy_po')->where(['buy_po_payId' => 0, 'fin_co2buy_id' => ['not in', $data['fin_co2buy_id']], 'po_id' => $v['id']])->sum('amount');
                $has_cost = hasData('fin_co2buy_po', ['fin_co2buy_id' => $data['fin_co2buy_id'], 'buy_po_payId' => 0, 'po_id' => $v['id']]);

                if ($returnData[$k]['cost_list']['amount'] - $costamount_sum == 0 && !$has_cost) {
                    unset($returnData[$k]['cost_list']);
                } else {
                    $returnData[$k]['cost_list']['price'] = $fin_co2buy_costamount;
                    $returnData[$k]['cost_list']['amount'] = $returnData[$k]['cost_list']['amount'] - $costamount_sum;
                    $returnData[$k]['cost_list']['paid'] = $returnData[$k]['cost_list']['paid'] - $fin_co2buy_costamount;
                }
            }
        }
        // dump($returnData);die;
        echo json_encode($returnData);
    }

    //处理日记账中的月账单详情权限
    public function journalmonthyear(Request $request)
    {
        $data = $request->param();
        $langcookie = cookie('think_var');
        //科目名称
        $finaccountins = getpostion('fin_account', $data['account_id']);//记账科目的上级id
        $name = implode('/', array_column(Db::name('fin_account')->field('name')->where('id', 'in', $finaccountins)->select(), 'name'));//记账科目名称

        //判断是否是不调整的收入
        $infofin = getinfo($data['account_id'], 'fin_account');

        //权限条件
        $admin = session('admin');
        $admin_authids = explode(",", $admin['auth_ids']);//权限
        $country_poid = getinfo($admin['position_id'], 'position')['country_id'];
        $posid = array_column(getFrames('position', null, $country_poid), 'id');
        array_push($posid, $admin['position_id']);//获取的是所有的职位
        $adminids = array_column(Db::name('admin')->field('id')->where('position_id', 'in', $posid)->select(), 'id');//获取能查看的员工的ids

        //时间条件
        $yearmonth = explode('-', date('Y-m-d', $data['happen_day']));
        $mapyearwhere['year'] = $mapmonthwhere['year'] = $yearmonth[0];
        $mapmonthwhere['month'] = $yearmonth[1];
        //科目条件
        $mapyearwhere['account_id'] = $mapmonthwhere['account_id'] = $data['account_id'];

        if ($infofin['adjust'] == 1) {
            $color = 'blue';
            $sign = '+';
        } elseif ($infofin['adjust'] == 2) {
            $color = 'red';
            $sign = '-';
        } else {
            $color = 'gray';
            $sign = '';
        }
        if ($request->isGet() && isset($data['month'])) {
            //月份查看
            if ($admin['position_id'] != 1) {
                if (in_array('177', $admin_authids) && !in_array('178', $admin_authids)) {
                    //查看自己下级的员工
                    $mapmonthwhere['create_id'] = ['in', $adminids];
                } elseif (in_array('176', $admin_authids) && !in_array('177', $admin_authids) && !in_array('178', $admin_authids)) {
                    //只能看自己的账单
                    $mapmonthwhere['create_id'] = $admin['id'];
                } else {
                    //默认看自己的月账单
                    $mapmonthwhere['create_id'] = $admin['id'];
                }
            }
            $datajountry = Db::name('journal')->where($mapmonthwhere)->select();
            $newview = 'journal/monthdeta';
        } elseif ($request->isGet() && isset($data['year'])) {
            //年份账单的显示
            if ($admin['position_id'] != 1) {
                if (in_array('177', $admin_authids) && !in_array('178', $admin_authids)) {
                    //查看自己和自己下级员工的年账单
                    $mapyearwhere['create_id'] = ['in', $adminids];
                } elseif (in_array('176', $admin_authids) && !in_array('177', $admin_authids) && !in_array('178', $admin_authids)) {
                    //只能看自己的年账单
                    $mapyearwhere['create_id'] = $admin['id'];
                } else {
                    //默认看自己的年账单
                    $mapyearwhere['create_id'] = $admin['id'];
                }
            }
            //一年中这个科目的所有收支情况
            $datajountry = Db::name('journal')->field('sum(amount) as amount,account_id,happen_day')->where($mapyearwhere)->group('month')->select();
            $newview = 'journal/yeardeta';
        }
        foreach ($datajountry as $datajountrykey => $datajountryval) {
            $datajountry[$datajountrykey]['amount'] = number_format($datajountryval['amount'], 3);
            if ($langcookie == 'zh-cn' || !$langcookie) {
                $datajountry[$datajountrykey]['happen_year'] = getTimeDate($datajountryval['happen_day'], 10);
                $datajountry[$datajountrykey]['happen_month'] = getTimeDate($datajountryval['happen_day'], 7);
            } else {
                $datajountry[$datajountrykey]['happen_year'] = getTimeDate($datajountryval['happen_day'], 11);
                $datajountry[$datajountrykey]['happen_month'] = getTimeDate($datajountryval['happen_day'], 8);
            }
        }
        $moneys = array_sum(array_column($datajountry, 'amount'));
        //合计，无论是收入，还是支出，不调整的合计
        $summoney = number_format($moneys, 3);
        return view($newview, [
            'name' => $name,
            'data' => $datajountry,
            'summoney' => $summoney,
            'color' => $color,
            'sign' => $sign
        ]);
    }

//日记账的保存请求接口
    public function journaladdedit(Request $request)
    {
        $data = $request->param();
        $journal = new \app\admin\model\Journal();
        if ($request->isPost() && $request->isAjax()) {
            $journalret = $journal->journaladdedit($data);
            $udata["status"] = $journalret['status'];
            $udata['msg'] = $journalret['msg'];
            echo json_encode($udata);
        }
    }

//日记账的编辑权限判断
    public function journaledit(Request $request)
    {
        $data = $request->param();
        $admin = session('admin');
        $admin_authids = explode(",", $admin['auth_ids']);
        $info = Db::name('journal')->field('id,happen_day,account_id,amount,remarks')->where('id', $data['id'])->find();
        $info['country_id'] = getinfo($info['account_id'], 'fin_account')['country_id'];
        $langcookie = cookie('think_var');
        if ($langcookie == 'zh-cn' || !$langcookie) {
            $info['happen_date'] = getTimeDate($info['happen_day'], 7);
        } else {
            $info['happen_date'] = getTimeDate($info['happen_day'], 13);
        }
        if ($admin['position_id'] != 1) {
            //确定用户的最高更改的最高权限
            if (in_array('171', $admin_authids)) {
                //拥有所有权限
                $udata["status"] = 1;
                $udata['msg'] = $info;
                echo json_encode($udata);
            } elseif (in_array('170', $admin_authids) && !in_array('171', $admin_authids)) {
                //拥有7天权限
                $time = (time() - $info['happen_day']) / 86400;
                if (ceil($time) > 7) {
                    $udata["status"] = 3;
                    $udata['msg'] =lang("no_permission,_please_contact_administrator");
                    echo json_encode($udata);
                } else {
                    $udata["status"] = 1;
                    $udata['msg'] = $info;
                    echo json_encode($udata);
                }
            } elseif (in_array('169', $admin_authids) && !in_array('170', $admin_authids) && !in_array('171', $admin_authids)) {
                //拥有3天权限
                $time = (time() - $info['happen_day']) / 86400;
                if (ceil($time) > 3) {
                    $udata["status"] = 3;
                    $udata['msg'] =lang("no_permission,_please_contact_administrator");
                    echo json_encode($udata);
                } else {
                    $udata["status"] = 1;
                    $udata['msg'] = $info;
                    echo json_encode($udata);
                }
            } elseif (in_array('168', $admin_authids) && !in_array('169', $admin_authids) && !in_array('170', $admin_authids) && !in_array('171', $admin_authids)) {
                //拥有当天的权限
                $time = (time() - $info['happen_day']) / 86400;
                if (ceil($time) > 1) {
                    $udata["status"] = 3;
                    $udata['msg'] = lang("no_permission,_please_contact_administrator");
                    echo json_encode($udata);
                } else {
                    $udata["status"] = 1;
                    $udata['msg'] = $info;
                    echo json_encode($udata);
                }
            } else {
                //没有权限
                $udata["status"] = 3;
                $udata['msg'] = lang("no_permission,_please_contact_administrator");
                echo json_encode($udata);
            }
        } else {
            $udata["status"] = 1;
            $udata['msg'] = $info;
            echo json_encode($udata);
        }
    }

    //日记账单的的删除权限
    public function journaldel(Request $request)
    {
        $data = $request->param();
        $admin = session('admin');
        $admin_authids = explode(",", $admin['auth_ids']);
        $info = Db::name('journal')->field('happen_day')->where('id', $data['id'])->find();
        //判断权限
        if ($request->isPost() && $request->isAjax()) {
            $journal = new \app\admin\model\Journal();
            if ($admin['position_id'] != 1) {
                //确定用户的最高的删除权限
                if (in_array('175', $admin_authids)) {
                    $journalret = $journal->journaldel($data);
                    $udata["status"] = $journalret['status'];
                    $udata['msg'] = $journalret['msg'];
                    echo json_encode($udata);
                } elseif (in_array('174', $admin_authids) && !in_array('175', $admin_authids)) {
                    //拥有7天权限
                    $time = (time() - $info['happen_day']) / 86400;
                    if (ceil($time) > 7) {
                        $udata["status"] = 3;
                        $udata['msg'] = lang("no_permission,_please_contact_administrator");
                        echo json_encode($udata);
                    } else {
                        $journalret = $journal->journaldel($data);
                        $udata["status"] = $journalret['status'];
                        $udata['msg'] = $journalret['msg'];
                        echo json_encode($udata);
                    }
                } elseif (in_array('173', $admin_authids) && !in_array('174', $admin_authids) && !in_array('175', $admin_authids)) {
                    //拥有3天权限
                    $time = (time() - $info['happen_day']) / 86400;
                    if (ceil($time) > 3) {
                        $udata["status"] = 3;
                        $udata['msg'] =lang("no_permission,_please_contact_administrator");
                        echo json_encode($udata);
                    } else {
                        $journalret = $journal->journaldel($data);
                        $udata["status"] = $journalret['status'];
                        $udata['msg'] = $journalret['msg'];
                        echo json_encode($udata);
                    }
                } elseif (in_array('172', $admin_authids) && !in_array('173', $admin_authids) && !in_array('174', $admin_authids) && !in_array('175', $admin_authids)) {
                    //拥有当天的权限
                    $time = (time() - $info['happen_day']) / 86400;
                    if (ceil($time) > 1) {
                        $udata["status"] = 3;
                        $udata['msg'] = lang("no_permission,_please_contact_administrator");
                        echo json_encode($udata);
                    } else {
                        $journalret = $journal->journaldel($data);
                        $udata["status"] = $journalret['status'];
                        $udata['msg'] = $journalret['msg'];
                        echo json_encode($udata);
                    }
                } else {
                    //没有权限
                    $udata["status"] = 3;
                    $udata['msg'] = lang("no_permission,_please_contact_administrator");
                    echo json_encode($udata);
                }
            } else {
                $journalret = $journal->journaldel($data);
                $udata["status"] = $journalret['status'];
                $udata['msg'] = $journalret['msg'];
                echo json_encode($udata);
            }
        }
    }

    //处理对excel的处理
    public function tlend()
    {
        require('PHPExcel/PHPExcel/IOFactory.php');
        //选取读取的文件
        $filename = 'lend.xlsx';
        $objPHPExcel = \PHPExcel_IOFactory::load($filename);//全部加载文件
        /*
         * 读取sheet中的内容1
         */
        $sheetCount = $objPHPExcel->getSheetCount();//读取excel文件有多少个sheet
        for ($i = 0; $i < $sheetCount; $i++) {
            $data = $objPHPExcel->getSheet($i)->toArray();//读取每一个sheet里面的数据，全部放到数组中
        }
        unset($data[0]);
        $resdatazh = array();
        $resdataen = array();
        $resdatapt = array();
        //去掉重复的内容
        $resdatazh = array();
        foreach ($data as $datakey => $dataval) {
            if ($dataval[1]) {
                if (!in_array($dataval[1], $resdatazh)) {
                    array_push($resdatazh, $dataval[1]);
                    array_push($resdataen, $dataval[2]);
                    array_push($resdatapt, $dataval[3]);
                }
            }
        }
        $arrone = array();
        $arrtwo = array();
        $arrthree = array();
        //中文
        foreach ($resdatazh as $resdatazhkey => $resdatazhval) {
            $abbreviation = str_replace(' ', '_', $resdataen[$resdatazhkey]);
            $arrone[] = array('lang' => 'zh', 'content' => $resdatazhval, 'abbreviation' => $abbreviation);
        }
        //英文
        foreach ($resdataen as $resdataenkey => $resdataenval) {
            $abbreviation = str_replace(' ', '_', $resdataenval);
            $arrtwo[] = array('lang' => 'en', 'content' => $resdataenval, 'abbreviation' => $abbreviation);
        }
        //葡文
        foreach ($resdatapt as $resdataptkey => $resdataptval) {
            $abbreviation = str_replace(' ', '_', $resdataen[$resdataptkey]);
            $arrthree[] = array('lang' => 'pt', 'content' => $resdataptval, 'abbreviation' => $abbreviation);
        }

//         $res = Db::name('dict')->where(['id'=>['>','339']])->delete();

        //写入数据
//        Db::name('dict')->insertAll($arrone);
//        Db::name('dict')->insertAll($arrtwo);
//        Db::name('dict')->insertAll($arrthree);

          dump($arrone);die;
//        dump($arrtwo);
        //dump($arrthree);
    }

    public function export_file()
    {    
        $data = Db::name('dict')->select();
        $name = 'dict_'.date("Y-m-d",time());
        $this->push($data,$name);
        // $this->redirect('export');
    }
 
     /* 导出excel函数*/
    public function push($data,$name='Excel')
    {
        // dump(PHPEXCEL_ROOT);die;
        // require('PHPExcel/PHPExcel.php');
        Vendor('PHPExcel.PHPExcel');//调用类库,路径是基于vendor文件夹的
        error_reporting(E_ALL);
        date_default_timezone_set('Europe/London');
        $objPHPExcel = new PHPExcel();
 
        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("转弯的阳光")
            ->setLastModifiedBy("转弯的阳光")
            ->setTitle("数据EXCEL导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
         /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
        foreach($data as $k => $v){
 
        $num=$k+1;
        $objPHPExcel->setActiveSheetIndex(0)//Excel的第A列，uid是你查出数组的键值，下面以此类推
                    ->setCellValue('A'.$num, $v['id'])   
                    ->setCellValue('B'.$num, $v['username'])
                    ->setCellValue('C'.$num, $v['password'])
                    ->setCellValue('D'.$num, $v['email'])
                    ->setCellValue('E'.$num, $v['head_ico'])
                    ->setCellValue('F'.$num, $v['invite'])
                    ->setCellValue('G'.$num, $v['is_seller_invite']);
        }

        $objPHPExcel->getActiveSheet()->setTitle('User');
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: applicationnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$name.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }

    public function getProcharCodebar()
    {
        $codebar = $this->verificationCodebar();
        return $codebar;
    }

    function verificationCodebar()
    {
        $codebarPrefix = '78997187';
        $rand = rand(1,9999);
        switch (strlen($rand)) {
            case '1':
                $codebar = $codebarPrefix.'000'.$rand;
                break;
            case '2':
                $codebar = $codebarPrefix.'00'.$rand;
                break;
            case '3':
                $codebar = $codebarPrefix.'0'.$rand;
                break;
            case '4':
                $codebar = $codebarPrefix.$rand;
                break;
        }

        $has = hasData('prochar',['codebar'=>$codebar]);
        if($has){
            $codebar = $this->verificationCodebar();
        }
        return $codebar;
    }
}
